import { defineStore } from 'pinia'

// 定义产品完善度信息的类型
interface ProductCompleteness {
  [productId: string]: string; // 产品ID -> 完善度值
}

// 定义 store
export const useCompletenessStore = defineStore('completeness', {
  // 状态
  state: () => ({
    // 产品完善度信息
    productCompleteness: {} as ProductCompleteness,
    // 当前查看的产品ID
    currentProductId: '',
  }),

  // getters
  getters: {
    // 获取指定产品的完善度
    getCompleteness: (state) => {
      return (productId: string) => {
        return state.productCompleteness[productId] || '0';
      }
    },
    // 获取当前查看的产品的完善度
    getCurrentCompleteness: (state) => {
      return state.productCompleteness[state.currentProductId] || '0';
    }
  },

  // actions
  actions: {
    // 设置产品完善度
    setCompleteness(productId: string, completeness: string) {
      this.productCompleteness[productId] = completeness;
    },
    // 设置当前查看的产品ID
    setCurrentProductId(productId: string) {
      this.currentProductId = productId;
    },
    // 批量设置产品完善度
    setMultipleCompleteness(completenessMap: ProductCompleteness) {
      this.productCompleteness = { ...this.productCompleteness, ...completenessMap };
    },
    // 从 sessionStorage 加载数据
    loadFromSessionStorage() {
      const storedData = sessionStorage.getItem('productCompleteness');
      if (storedData) {
        try {
          this.productCompleteness = JSON.parse(storedData);
        } catch (e) {
          console.error('Failed to parse productCompleteness from sessionStorage:', e);
        }
      }

      const currentId = sessionStorage.getItem('lastViewedProductId');
      if (currentId) {
        this.currentProductId = currentId;
      }
    },
    // 保存数据到 sessionStorage
    saveToSessionStorage() {
      sessionStorage.setItem('productCompleteness', JSON.stringify(this.productCompleteness));
      if (this.currentProductId) {
        sessionStorage.setItem('lastViewedProductId', this.currentProductId);
      }
    }
  }
}) 